package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.pojo.SetmealNameCount;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wq
 * @TIME 2023/1/5 5:55 下午
 * @description 登录验证Controller
 */

@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private ReportService reportService;

    /**
     * 统计分析-套餐占比（饼形图）
     * SetmealNameCount:保存套餐名称数组（String[] setmealNames）及各套餐数量的数组（Map[] setmealCount）的pojo
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport() {
//        Integer[] setmealIds = orderService.findSetmealId();
//        List<String> setmealNameList = new ArrayList<>();
//        for (Integer setmealId : setmealIds) {
//            Setmeal setmeal = setMealService.findSetmealNameById(setmealId);
//            setmealNameList.add(setmeal.getName());
//        }
//        System.out.println(setmealNameList);
        List<String> setmealNames = setMealService.findSetmealNamesByIds();
        String[] setmealNameArray = setmealNames.toArray(new String[setmealNames.size()]);
        Map[] setmealCount = new Map[setmealNameArray.length];
        for (int i = 0; i < setmealNameArray.length; i++) {
            Map<String, Object> map = new HashMap<>();
            Integer setmealId = setMealService.findByName(setmealNameArray[i]);
            Integer count = orderService.findCount(setmealId);
            map.put("name", setmealNameArray[i]);
            map.put("value", count);
            setmealCount[i] = map;
        }
        return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS, new SetmealNameCount(setmealNameArray, setmealCount));
    }

    /**
     *
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String, Object> businessReportData = reportService.getBusinessReportData();
        return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS, businessReportData);
    }

    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response) throws IOException {
        //获取运营统计的数据
        Map<String, Object> reportData = reportService.getBusinessReportData();
        String reportDate= (String) reportData.get("reportDate");
        Integer todayVisitsNumber = (Integer) reportData.get("todayVisitsNumber");
        Integer thisWeekVisitsNumber = (Integer) reportData.get("thisWeekVisitsNumber");
        Integer thisMonthVisitsNumber = (Integer) reportData.get("thisMonthVisitsNumber");
        Integer todayOrderNumber = (Integer) reportData.get("todayOrderNumber");
        Integer thisWeekOrderNumber = (Integer) reportData.get("thisWeekOrderNumber");
        Integer thisMonthOrderNumber = (Integer) reportData.get("thisMonthOrderNumber");
        Integer todayNewMember = (Integer) reportData.get("todayNewMember");
        Integer thisWeekNewMember = (Integer) reportData.get("thisWeekNewMember");
        Integer thisMonthNewMember = (Integer) reportData.get("thisMonthNewMember");
        Integer totalMember = (Integer) reportData.get("totalMember");
        List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");
        OutputStream outputStream = response.getOutputStream();
        //根据输入流创建一个excel对象
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        sheet.getRow(2).getCell(5).setCellValue(reportDate);
        sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
        sheet.getRow(4).getCell(7).setCellValue(totalMember);
        sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
        sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
        sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
        sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
        sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
        sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
        sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
        sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);

        int rowNumber=12;
        for (Map setmeal : hotSetmeal) {
            //获取12行的行对象
            //查询到的热点数据，需要与模板中的存储热点数据的行数一致，如果热点数据多于模板中excel存储热点数据的行数，会报空指针异常
            Row row = sheet.getRow(rowNumber);
            //对行对象进行赋值
            row.getCell(4).setCellValue((String) setmeal.get("name"));
            row.getCell(5).setCellValue((Long) setmeal.get("setmeal_count"));
            row.getCell(6).setCellValue(((BigDecimal) setmeal.get("proportion")).doubleValue());
            rowNumber++;
        }
        //写入excel的固定写法
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;fileName=" + reportDate + "_report.xlsx");
        workbook.write(outputStream);
        return new Result(true,MessageConst.ACTION_SUCCESS);
    }

    @GetMapping("/getMemberReport")
    public Result getMemberReport() {
        List<String> months = new ArrayList<>();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM");
        Calendar cal = Calendar.getInstance();
        //用当前时间的月份减去12个月，用来统计前一年每个月的会员数量
        cal.add(Calendar.MONTH,-12);
        //System.out.println(cal.getTime());
        for (int i = 0; i < 12; i++) {
            //把当前月份添加到months集合（当前月份为现在系统时间的月份减去12个月，如现在为2023.01，12月之前就是2022.01）
            months.add(sdf1.format(cal.getTime()));
            //让减去12个月的时间加上一个月，表示下一个月
            cal.add(Calendar.MONTH,1);
        }
        List<Integer> memberCount = reportService.getMemberCountByMonths(months);
        Map<String, Object> map = new HashMap<>();
        map.put("months", months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);

    }
}
